import Vue from 'vue';

export default {
  // 请求数
  requestCount: 0,

  /**
   * 显示loading
   * @param  {Boolean} status false 关闭 true 显示
   */
  loading(status) {
    if (status == false) {
      this.requestCount--;
      this.requestCount < 1 && Vue.$vux.loading.hide();
      return;
    }
    this.requestCount++;
    Vue.$vux.loading.show({
      text: (typeof status == 'object') ? status.text : '加载中...'
    });
  },
  alert({title = '提示', buttonText = '确认', content = '', onHide = null} = {}) {
    Vue.$hscf.alert.show({
      title,
      buttonText,
      content,
      onHide: () => {
        typeof onHide == 'function' && onHide();
      }
    });
  },
  confirm({title = '提示', cancelText = '取消', confirmText = '确认', content = '', onCancel = null, onConfirm = null} = {}) {
    Vue.$vux.confirm.show({
      title,
      cancelText,
      confirmText,
      content,
      onCancel: () => {
        typeof onCancel == 'function' && onCancel();
      },
      onConfirm: () => {
        typeof onConfirm == 'function' && onConfirm();
      }
    })
  },
  toast({content = '', type = 'text', time = 1500, width = 'auto', isShowMask = false, onHide = null} = {}) {
    Vue.$vux.toast.show({
      text: content,
      type,
      time,
      width,
      isShowMask,
      onHide: () => {
        typeof onHide == 'function' && onHide();
      }
    });
  },
  propmt({closeOnConfirm = true, showInput = true, title = '提示', placeholder = '', buttonText = '确认', onCancel = null, onConfirm = null} = {}) {
    Vue.$vux.confirm.show({
      closeOnConfirm,
      showInput,
      title,
      placeholder,
      buttonText,
      onCancel: () => {
        typeof onCancel == 'function' && onCancel();
      },
      onConfirm: (val) => {
        typeof onConfirm == 'function' && onConfirm(val);
      }
    })
  },

  aes(data, aeskey = '1234567897654321') {
    return CryptoJS.AES.encrypt((typeof data === 'object' ? JSON.stringify(data) : data), CryptoJS.enc.Utf8.parse(aeskey), {
      mode: CryptoJS.mode.ECB,
      padding: CryptoJS.pad.Pkcs7
    }).toString();
  },

  /**
   * 时间日期格式化
   * @param  {[String, Number]} v      时间日期字符串（iso 8601）
   * @param  {[String]} format 转换后的日期格式 如： yyyy-MM-dd HH:mm:ss = 2017-10-12 10:33:52
   * @return {[String]}        转换后的时间字符串
   */
  dateFormat(v, format) {
    if (!v) return '';
    if (typeof v === 'string') {
      v = v.replace(/\-/g, "/");
    }
    v = new Date(v);
    let o = {
      "M+": v.getMonth() + 1,
      "d+": v.getDate(),
      "h+": v.getHours(),
      "m+": v.getMinutes(),
      "s+": v.getSeconds(),
      "q+": Math.floor((v.getMonth() + 3) / 3),
      "S": v.getMilliseconds()
    };
    if (/(y+)/.test(format))
      format = format.replace(RegExp.$1, (v.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (let k in o)
      if (new RegExp("(" + k + ")").test(format))
        format = format.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return format;
  },

  setCookie(name, value, Days = 30) {
    const exp = new Date();
    exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);
    document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString();
  },

  getCookie(name) {
    let arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
    if (arr = document.cookie.match(reg))
      return arr[2];
    else
      return null;
  },

  delCookie(name) {
    const exp = new Date();
    exp.setTime(exp.getTime() - 1);
    const cval = this.getCookie(name);
    if (cval !== null)
      document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString();
  },

  /**
   * 判断设备是否是移动端
   * @return {Boolean} [description]
   */
  isPhone() {
    const Agents = new Array("Android", "iPhone", "SymbianOS", "Windows Phone", "iPad", "iPod");
    let flag = false;
    for (var v = 0; v < Agents.length; v++) {
      if (userAgentInfo.indexOf(Agents[v]) >= 0) {
        flag = true;
        break;
      }
    }
    return flag;
  },

  isIphone() {
    return /iPhone|iPad|iPod/.test(navigator.userAgent);
  },

  isAndroid() {
    const u = navigator.userAgent;
    return u.indexOf('Android') > -1 || u.indexOf('Adr') > -1;
  },

  isEmptyObject(obj) {
    for (let name in obj) {
      return false;
    }
    return true;
  },

  parsePostData(obj) {
    let result = [];
    for (let key in obj) {
      result.push(key + '=' + encodeURIComponent(obj[key]));
    }
    return result.join('&');
  },

  /**
   * https://developer.mozilla.org/zh-CN/docs/Web/API/Fetch_API
   * https://developer.mozilla.org/zh-CN/docs/Web/API/GlobalFetch/fetch
   *
   * fetch请求
   * @param  {[Object]} options
   * @return {[Object]} promise
   */
  request(options) {
    options.showErrorMsg = options.showErrorMsg !== false;
    options.loading !== false && this.loading();

    options.url = `http://www.mangobanker.com/api${options.url}`;

    if (options.dataType === 'json') {
      if (options.data) {
        options.data = {
          data: options.data,
        };
      } else  {
        options.data = {};
      }

      const token = this.getCookie('token');

      if (token) {
        options.data.header = {
          token: this.getCookie('token'),
        }
      }
    }

    let queryString, config = {
      method: options.method || 'get',
      headers: {
        token: this.getCookie('token'),
      }
    };

    if (options.dataType === 'json') {
      config.method = 'post';
      config.headers['content-type'] = 'application/json;charset=UTF-8';
      config.body = (typeof options.data === 'string') ? options.data : JSON.stringify(options.data);
    } else if (config.method === 'post') {
      config.headers['content-type'] = 'application/json;charset=UTF-8';
//    config.headers['content-type'] = 'application/x-www-form-urlencoded';
      config.body = (typeof options.data === 'string') ? options.data : JSON.stringify(options.data);
    } else if (config.method === 'get') {
      queryString = this.parsePostData(options.data);
    }

    let newFetch = Promise.race([fetch(queryString ? `${options.url}?${queryString}` : options.url, config), new Promise(function (resolve, reject) {
      setTimeout(() => {
        reject(new Error("请求超时，请稍后再试"));
      }, options.timeout || 20000)
    })]);

    return newFetch.then(response => {
      const status = response.status;
      switch (true) {
        case status === 400:
          throw new Error('请求参数错误');
        case status === 405:
          throw new Error('请求方式不正确');
          break;
        case status === 415:
          throw new Error('参数格式不正确');
          break;
        case status === 404:
          throw new Error('请求的接口不存在');
          break;
        case status >= 500:
          throw new Error('接口错误：' + status);
          break;
        default:
          return response.json();
          break;
      }
    }).then(data => {
      this.loading(false);
      return data;
    }).catch((error) => {
      this.loading(false);
      mui.toast({content: msg});
    });
  },

  /**
   * 移动端屏幕适配
   * @param  {Number} designWidth 设计稿宽度
   * @param  {Number} rem2px      转换比例
   * @return {Function}           转换函数
   */
  adaptor(designWidth, rem2px) {
    const set = () => {
      document.documentElement.style.fontSize = ((window.innerWidth / designWidth) * rem2px) + 'px';
    };
    set();
    window.onresize = set;
    return set;
  },
  fillZero(num, length = 2) {
    if (num >= 10) {
      return num + '';
    }

    num = (num + '').padStart(length, '0');
    return num.slice(-length);
  }
}
